package com.mystore.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

@WebFilter(filterName = "CharSetEncodingFilter",urlPatterns ={"/*"},
        initParams = {
                @WebInitParam(name = "encoding",value = "utf-8")
        }
)
public class CharSetEncodingFilter implements Filter {
    private String encoding;
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("CharSetEncodingFilter.....");
        if(encoding==null){
            encoding = "UTF-8";
        }
        //设置request字符编码
        req.setCharacterEncoding(encoding);
        //设置response字符编码
        resp.setContentType("text/html;charset="+encoding);

        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {
        this.encoding=config.getInitParameter("encoding");
    }

}
